package com.morn.weibo;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.j256.ormlite.android.apptools.OrmLiteBaseActivity;
import com.j256.ormlite.dao.Dao;
import com.morn.weibo.db.FanfouOpenHelper;
import com.morn.weibo.http.Fanfou;
import com.morn.weibo.types.User;
import com.morn.weibo.types.UserAccount;

public class LoginActivity extends OrmLiteBaseActivity<FanfouOpenHelper> {
	private EditText etLoginName;
	private EditText etLoginPassword;
	private TextView tvRegist;
	private Button btLogin;
	private Fanfou fanfou;
	private Dialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_login);
		fanfou = WeiboApplication.getFanfou();
		init();
	}

	private void init() {
		etLoginName = (EditText) findViewById(R.id.etLoginName);
		etLoginPassword = (EditText) findViewById(R.id.etLoginPassword);
		btLogin = (Button) findViewById(R.id.btLogin);
		tvRegist = (TextView) findViewById(R.id.tvRegist);
		tvRegist.setText(Html.fromHtml(getResources().getString(
				R.string.regist_url)));
		tvRegist.setMovementMethod(LinkMovementMethod.getInstance());
		btLogin.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				login();
			}
		});
		TextWatcher fieldValidatorTextWatcher = new TextWatcher() {
			@Override
			public void afterTextChanged(Editable s) {
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				btLogin.setEnabled(userNameTextFieldIsValid()
						&& passwordTextFieldIsValid());
			}

			private boolean userNameTextFieldIsValid() {
				return !TextUtils.isEmpty(etLoginName.getText());
			}

			private boolean passwordTextFieldIsValid() {
				return !TextUtils.isEmpty(etLoginPassword.getText());
			}
		};
		etLoginName.addTextChangedListener(fieldValidatorTextWatcher);
		etLoginPassword.addTextChangedListener(fieldValidatorTextWatcher);
	}

	private void login() {
		UserAccount userAccount = new UserAccount();
		userAccount.setUserName(etLoginName.getText().toString());
		userAccount.setUserPassword(etLoginPassword.getText().toString());
		final LoignAsyncTask loignAsyncTask = new LoignAsyncTask();
		dialog = ProgressDialog.show(LoginActivity.this, null,
				getString(com.morn.weibo.R.string.login_loading), true, false);
		dialog.setOnDismissListener(new OnDismissListener() {
			@Override
			public void onDismiss(DialogInterface dialog) {
				loignAsyncTask.cancel(true);
			}
		});
		new LoignAsyncTask().execute(userAccount);
	}

	private class LoignAsyncTask extends AsyncTask<Object, Object, String> {

		private User user;
		private UserAccount userAccount;

		@Override
		protected String doInBackground(Object... params) {
			userAccount = (UserAccount) params[0];
			String result = "";
			try {
				fanfou.setCredentials(userAccount);
				user = fanfou.verifyAccount();
			} catch (Exception e) {
				e.printStackTrace();
				result = e.getMessage();
			}
			return result;
		}

		@Override
		protected void onPostExecute(String result) {
			dialog.dismiss();
			if (!isCancelled()) {
				if (user != null) {
					try {
						Dao<User, String> userDao = getHelper().getUserDao();
						userDao.create(user);
						Dao<UserAccount, Integer> userAccountdao = getHelper()
								.getUserAccountDao();
						userAccount.setUser(user);
						userAccountdao.create(userAccount);
						Intent intentMain = new Intent(LoginActivity.this,
								MainActivity.class);
						LoginActivity.this.startActivity(intentMain);
						LoginActivity.this.finish();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} else {
					fanfou.clearCredentials();
					Toast.makeText(LoginActivity.this, result,
							Toast.LENGTH_SHORT).show();
				}
			}
		}

		@Override
		protected void onCancelled() {

		}

	}
}
